<template>
  <div class="page-container">
    <h1 class="page-title">🚶 路径规划</h1>
    
    <!-- 天气卡片 -->
    <div class="card weather-card" v-if="weather">
      <div class="weather-icon">{{ getWeatherIcon(weather.condition) }}</div>
      <div class="weather-info">
        <h3>{{ weather.condition }} {{ weather.temperature }}°C</h3>
        <p>湿度: {{ weather.humidity }}% | 风速: {{ weather.wind_speed }}km/h</p>
      </div>
    </div>
    
    <!-- 位置状态 -->
    <div class="card">
      <div v-if="loading" class="loading">
        <div class="loading-spinner"></div>
      </div>
      <div v-else-if="locationError" class="error-message">
        <p>{{ locationError }}</p>
        <button class="btn btn-primary" @click="getLocation">重新获取位置</button>
      </div>
      <div v-else-if="currentLocation">
        <p>📍 当前位置: {{ currentLocation.latitude.toFixed(6) }}, {{ currentLocation.longitude.toFixed(6) }}</p>
      </div>
    </div>
    
    <!-- 景点列表 -->
    <div class="card" v-if="pois.length > 0">
      <h3 style="margin-bottom: 16px;">附近景点</h3>
      <div class="poi-list">
        <div 
          v-for="poi in pois" 
          :key="poi.id" 
          class="poi-item"
          :class="{ selected: selectedPoi?.id === poi.id }"
          @click="selectPoi(poi)"
        >
          <div class="poi-info">
            <h4>{{ poi.name }}</h4>
            <p>{{ poi.category }} | ⭐ {{ poi.rating || '暂无评分' }}</p>
          </div>
          <div class="poi-distance">{{ formatDistance(poi.distance) }}</div>
        </div>
      </div>
    </div>
    
    <!-- 空状态 -->
    <div class="empty-state" v-else-if="!loading && currentLocation">
      <img src="/images/route.png" alt="无景点">
      <p>附近暂无景点</p>
      <p style="font-size: 14px;">请尝试扩大搜索范围</p>
    </div>
    
    <!-- 开始散步按钮 -->
    <div style="text-align: center; margin-top: 20px;" v-if="selectedPoi">
      <button class="btn btn-primary" @click="startWalking" :disabled="startingSession">
        {{ startingSession ? '正在启动...' : '开始散步' }}
      </button>
    </div>
  </div>
</template>

<script>
import { getCurrentLocation, formatDistance } from '../utils/location'
import { routeApi, weatherApi, sessionApi } from '../utils/api'

export default {
  name: 'RoutePlanner',
  data() {
    return {
      loading: false,
      currentLocation: null,
      locationError: null,
      weather: null,
      pois: [],
      selectedPoi: null,
      startingSession: false
    }
  },
  mounted() {
    this.getLocation()
  },
  methods: {
    formatDistance,
    
    async getLocation() {
      this.loading = true
      this.locationError = null
      
      try {
        this.currentLocation = await getCurrentLocation()
        await this.loadWeather()
        await this.searchPOIs()
      } catch (error) {
        this.locationError = error.message
      } finally {
        this.loading = false
      }
    },
    
    async loadWeather() {
      if (!this.currentLocation) return
      
      try {
        const response = await weatherApi.getCurrent(
          this.currentLocation.latitude,
          this.currentLocation.longitude
        )
        this.weather = response.data || response
      } catch (error) {
        console.error('获取天气失败:', error)
      }
    },
    
    async searchPOIs() {
      if (!this.currentLocation) return
      
      try {
        const response = await routeApi.searchPOIs(
          this.currentLocation.latitude,
          this.currentLocation.longitude
        )
        this.pois = response.data || response.pois || []
      } catch (error) {
        console.error('搜索景点失败:', error)
        this.pois = []
      }
    },
    
    selectPoi(poi) {
      this.selectedPoi = this.selectedPoi?.id === poi.id ? null : poi
    },
    
    async startWalking() {
      if (!this.selectedPoi || !this.currentLocation) return
      
      this.startingSession = true
      
      try {
        // 生成路径
        const routeResponse = await routeApi.generateRoute(
          this.currentLocation,
          this.selectedPoi.id
        )
        
        // 创建会话
        const sessionResponse = await sessionApi.start(
          this.selectedPoi.id,
          routeResponse.data || routeResponse
        )
        
        // 保存会话信息并跳转到导航页面
        localStorage.setItem('currentSession', JSON.stringify({
          sessionId: sessionResponse.session_id || sessionResponse.id,
          poi: this.selectedPoi,
          route: routeResponse.data || routeResponse
        }))
        
        this.$router.push('/navigation')
      } catch (error) {
        console.error('启动散步失败:', error)
        alert('启动散步失败，请重试')
      } finally {
        this.startingSession = false
      }
    },
    
    getWeatherIcon(condition) {
      const icons = {
        '晴': '☀️',
        '多云': '⛅',
        '阴': '☁️',
        '雨': '🌧️',
        '雪': '❄️',
        '雾': '🌫️'
      }
      return icons[condition] || '🌤️'
    }
  }
}
</script>
